package spt.tasks;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * TaskManager is responsible for executing background tasks.
 * @author Piotr Procner
 *
 */
public class TaskManager extends Thread{
	private final Logger log = Logger.getLogger(TaskManager.class.getName());
	
	/**
	 * Default time in seconds between tasks executing.
	 */
	private final int DEFAULT_INTERVAL = 3600; //1h
	
	private List<Task> tasks;
	private int interval;
	
	private boolean running;
	
	/**
	 * Default constructor. Sets interval to default value - in this case 600 seconds. 
	 */
	public TaskManager(){
		tasks = new ArrayList<Task>();
		interval = DEFAULT_INTERVAL;
		running = false;
	}
	
	/**
	 * Constructor. Sets interval as specified in parameter.
	 * @param interval Time between tasks executing.
	 */
	public TaskManager(int interval){
		this();
		this.interval = interval;
	}
	
	/**
	 * Adds task to the task queue.  
	 * @param task Task to execute. 
	 */
	public void addTask(Task task){
		tasks.add(task);
	}
	
	/**
	 * Removes task from the task queue.
	 * @param task Task to remove.
	 */
	public void removeTask(Task task){
		tasks.remove(task);
	}
	
	/**
	 * Sets time between tasks executing.
	 * @param interval Interval.
	 */
	public void setInterval(int interval){
		this.interval = interval;
	}
	
	/**
	 * Starts repetitively execute tasks. 
	 */
	public void run(){
		running = true;
		while(running){
			log.info("Executing jobs.");
			for(Task task : tasks)
				task.execute();
			try {
				Thread.sleep(interval * 1000);
			} catch (InterruptedException e) {
				log.severe(e.getMessage());
			}
		}
	}
	
	/**
	 * Stop tasks executing.
	 */
	public void stopThread(){
		running = false;
	}
}
